package com.szbmyoubao.app.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.szbmyoubao.app.base.vm.PageIntent
import com.szbmyoubao.app.base.vm.PageState
import com.szbmyoubao.app.bean.response.BaseListResponse
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.loadState.LoadState.*
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.ellecity06.common.adapter.CustomLoadMoreAdapter
import com.ellecity06.common.base.BaseAdapter
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.base.BaseViewModel
import com.ellecity06.common.databinding.LayoutEmptyViewBinding
import com.ellecity06.common.ktx.clearAnimations
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.onDebounceClick
import com.ellecity06.common.utils.ToastUtils
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * @author ellecity06
 * @time 2025/1/2 17:50
 * @des 列表 fragment
 */
abstract class BasePageFragment<VB : ViewBinding, out VM : BaseViewModel> : BaseMvvmFragment<VB, VM>(), TrailingLoadStateAdapter.OnTrailingListener,
    OnRefreshListener {
    open val refreshLayout: SmartRefreshLayout? = null
    open val recyclerView: RecyclerView? = null

    /**
     * 要是用lazy 保证唯一
     */
    open val adapter: BaseAdapter<*, out ViewBinding>? = null
    protected var adapterHelper: QuickAdapterHelper? = null
    open val layoutManager: RecyclerView.LayoutManager by lazy { LinearLayoutManager(requireActivity()) }

    /**
     * 是否开启加载更多
     */
    open val enableLoadMore: Boolean = true

    /**
     * 是否开启加载更多
     */
    open val enableEmpty: Boolean = true

    private val emptyViewBinding by lazy { LayoutEmptyViewBinding.inflate(LayoutInflater.from(requireActivity()), recyclerView, false) }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        handlerView()
        collectPageState()
    }

    private fun handlerView() {
        refreshLayout?.setOnRefreshListener(this)
        recyclerView?.layoutManager = layoutManager
        recyclerView?.clearAnimations()
        recyclerView?.let {
            if (enableEmpty) {
                adapter?.emptyView = emptyViewBinding.root
            }
            adapter?.isEmptyViewEnable = true
            emptyViewBinding.ivEmpty.onDebounceClick(::onEmptyClick)
            emptyViewBinding.tvTips.onDebounceClick(::onEmptyClick)

            if (enableLoadMore) {
                val loadMoreAdapter = CustomLoadMoreAdapter()
                loadMoreAdapter.setOnLoadMoreListener(this)
                adapterHelper = QuickAdapterHelper.Builder(adapter!!)
                    .setTrailingLoadStateAdapter(loadMoreAdapter)
                    .build()
//                adapterHelper?.trailingLoadStateAdapter?.isAutoLoadMore = false
                handlerAdapterHelper()
                recyclerView?.adapter = adapterHelper?.adapter
            } else {
                recyclerView?.adapter = adapter
            }

        }

    }

    open fun handlerAdapterHelper() {
    }

    open fun onEmptyClick(view: View) {
        refresh()
    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        refresh()
    }

    protected fun refresh() {
        if (viewModel is BasePageViewModel<*, *>) {
            lifecycleScope.launchWhenCreated {
                (viewModel as BasePageViewModel<*, *>).pageIntent.send(PageIntent.Refresh)
            }

        }
    }

    private fun loadMore() {
        if (viewModel is BasePageViewModel<*, *>) {
            lifecycleScope.launchWhenCreated {
                (viewModel as BasePageViewModel<*, *>).pageIntent.send(PageIntent.LoadMore)
            }
        }
    }

    open fun collectPageState() {
        if (viewModel is BasePageViewModel<*, *>) {
            (viewModel as BasePageViewModel<*, *>).pageState.observeEvent(this) {
                when (it) {
                    PageState.LoadError -> {
                        refreshLayout?.finishRefresh()
                    }

                    is PageState.LoadMoreSuccess -> {
                        addList(it.list)
                        adapterHelper?.trailingLoadState = NotLoading(!it.hasMore)
                    }

                    PageState.NoMore -> {
                        refreshLayout?.finishRefresh()
                        adapterHelper?.trailingLoadState = None
                    }

                    is PageState.RefreshSuccess -> {
                        submitList(it.list)
                        refreshLayout?.finishRefresh()
                        if (it.hasMore) {
                            adapterHelper?.trailingLoadState = NotLoading(false)
                        } else {
                            adapterHelper?.trailingLoadState = None
                        }
                    }

                    is PageState.RefreshError -> {
                        refreshLayout?.finishRefresh()
                        ToastUtils.show(it.msg)
                    }

                    is PageState.ExtDate ->
                        onExData(it.ext)
                }
            }
        }
    }

  open fun onExData(response: BaseListResponse.ExtResponse) {
    }

    open fun addList(list: List<*>) {
        adapter?.addAll(list as List<Nothing>)
    }

    open fun submitList(list: List<*>) {
        adapter?.submitList(list as List<Nothing>)
    }

    override fun onFailRetry() {
        loadMore()
    }

    override fun onLoad() {
        loadMore()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        adapterHelper = null
    }
}